import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Main from '../views/Main.vue'
import Profile from '../views/Profile.vue'
import RiderCenter from '../views/RiderCenter.vue'
import Payment from '../views/Payment.vue'
import Orders from '../views/Orders.vue'
import Merchant from '../views/Merchant.vue' // 导入商家管理组件
import PaymentComplete from '../views/PaymentComplete.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/merchant',
    name: 'merchant',
    component: Merchant,
    meta: { requiresAuth: true, requiresAdmin: true } // 添加meta字段用于权限控制
  },
  {
    path: '/',
    name: 'home',
    component: Main
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },
  {
    path: '/main',
    name: 'main',
    component: Main
  },
  {
    path: '/profile',
    name: 'profile',
    component: Profile
  },
  {
    path: '/rider',
    name: 'rider',
    component: RiderCenter
  },
  {
    path: '/payment',
    name: 'payment',
    component: Payment
  },
  {
    path: '/orders',
    name: 'orders',
    component: Orders
  },
  {
    path: '/payment-complete',
    name: 'payment-complete',
    component: PaymentComplete
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const loggedIn = localStorage.getItem('userInfo');
  const userInfo = loggedIn ? JSON.parse(loggedIn) : null;

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!loggedIn) {
      next('/login');
    } else {
      if (to.matched.some(record => record.meta.requiresAdmin)) {
        if (userInfo && userInfo.type === 2) {
          next();
        } else {
          alert('您没有权限访问此页面');
          next(from.path || '/'); // 或者跳转到无权限提示页面
        }
      } else {
        next();
      }
    }
  } else {
    next();
  }
});

export default router
